import type { UploadFileType } from '@/api/base/interface'
import { upload } from '@/api/base'
import { useState } from 'react'

export type FileItem = {
    name?: string
    url: string
    thumbnailUrl?: string
    size?: number
    extra?: {
        name: string
    }
}

export interface Props<F extends FileItem = FileItem> {
    fileList?: F[]
    accept?: string
    maxSize?: number
    maxCount?: number
    cleanBeforeUpload?: boolean
    uploadFileType?: UploadFileType
    onChange?: (fileList: F[]) => any
}

/**
 * 上传文件
 *
 */
const useUpload = <F extends FileItem = FileItem>(props: Props<F>) => {
    const defaultFileList = props.fileList ?? []
    const { maxSize = 30, maxCount } = props

    const [fileList, setFileList] = useState<FileItem[]>(defaultFileList)

    /**
     * 上传拦截器
     * @param file
     */
    const beforeUpload = (file: Omit<FileItem, 'url'>) => {
        const { name } = file

        if (props.accept !== undefined && name !== undefined) {
            const acceptList = props.accept.split(',')
            if (!acceptList.some(accept => name.lastIndexOf(accept) !== -1))
                return { msg: '不支持当前文件格式', approve: false }
        }

        // 上传前重置文件列表（用于一个文件数量限制时替换文件）
        if (props.cleanBeforeUpload) {
            setFileList([])
        }

        // 文件上传总数校验
        if (!props.cleanBeforeUpload && fileList.length === props.maxCount) {
            return { msg: `最多上传${maxCount}个`, approve: false }
        }

        // 文件大小校验
        if (maxSize !== undefined) {
            if (file.size && file.size / 1024 / 1024 >= maxSize) {
                return { msg: `文件大小不能超过${maxSize}MB`, approve: false }
            }
        }

        return { msg: '成功', approve: true }
    }

    /**
     * 自定义上传
     * @param opts
     */
    const defaultUpload = async (params: { file: File; onSuccess?: (...args: any[]) => any }) => {
        const { data } = await upload({ file: params.file, type: props.uploadFileType })
        params.onSuccess?.(data)

        return data
    }

    return { fileList, setFileList, beforeUpload, defaultUpload }
}

export default useUpload
